package com.budwk.app.sys.commons.task.job;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.fetchdata.models.FetchData_emergency;
import com.budwk.app.fetchdata.services.FetchdataEmergencyService;

import com.budwk.app.miniapp.utils.AddressUtils;


import com.budwk.app.miniapp.utils.HttpUtils;
import com.budwk.starter.email.EmailSendServer;
import com.budwk.starter.job.annotation.SJob;
import lombok.extern.slf4j.Slf4j;
import org.nutz.dao.Cnd;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;


@Slf4j
@IocBean(name = "pullEarthQuakeDataService",singleton = false)
public class PullEarthQuakeDataService {

    @Inject
    private FetchdataEmergencyService wxSpiderEmergencyInformationService;

    @Inject
    private EmailSendServer emailSendServer;

    @Inject
    private PropertiesProxy propertiesProxy;

    @Inject("taskQueryExecutor")
    private ThreadPoolExecutor taskQueryExecutor;

    /**
     * 中囯地震台网
     * @return
     */
    @SJob("earthQuakeData")
    public void earthQuakeData(String taskId, String params) {
        try {
            System.out.println("中国地震台网: "+new Date());
            List<FetchData_emergency> emergencyInfoList = new ArrayList<>();

            String result = HttpUtils.getRequest("http://140.210.211.155:8089/datapi/earthquakedata/query?pageNumber=1&pageSize=50");
            JSONObject dataJson = JSONObject.parseObject(result);
            JSONObject pagerJson = dataJson.getJSONObject("data");
            JSONArray listJson = pagerJson.getJSONArray("list");

            try {


                for (int i = 0; i < listJson.size(); i++) {

                    JSONObject item = listJson.getJSONObject(i);
                    FetchData_emergency infoBo = new FetchData_emergency();
                    infoBo.setInformationtitle(item.getString("LOCATION_C")+"发生了"+item.getString("M")+"级地震");
                    String startDate =item.getString("O_TIME").replaceAll("/","-");
                    infoBo.setReleasetime(Timestamp.valueOf(startDate));

                    FetchData_emergency vo = wxSpiderEmergencyInformationService.fetch(Cnd.where(FetchData_emergency::getInformationtitle,"=",infoBo.getInformationtitle())
                            .and(FetchData_emergency::getReleasetime,"=",infoBo.getReleasetime()));
                    if(ObjectUtil.isEmpty(vo)) {
                            JSONObject addressInfo = AddressUtils.getAddressInfo(item.getString("EPI_LON"), item.getString("EPI_LAT"));
                            JSONObject  jsonresult= addressInfo.getJSONObject("result");

                            if(jsonresult!=null) {
                                String formatted_address = jsonresult.getString("formatted_address");
                                JSONObject addressComponent = jsonresult.getJSONObject("addressComponent");
                                String province = addressComponent.getString("province");
                                String city = addressComponent.getString("city");
                                String county = addressComponent.getString("county");
                               // String district = addressComponent.getString("road");
                                // String poi = addressComponent.getString("poi");
                                if(StrUtil.isNotBlank(province)&&StrUtil.isNotBlank(city)&&StrUtil.isNotBlank(county)) {
                                    infoBo.setDisaster_address(province + city + county);
                                }
                                if(StrUtil.isBlank(province)) {
                                    infoBo.setDisaster_address(item.getString("LOCATION_C")+"【国外】");
                                }
                                infoBo.setProvince(province);
                                infoBo.setCity(city);
                                infoBo.setDistrict(county);
                               // infoBo.setStreet(district);
//                                if(poi!=null&&poi.contains("村"))
//                                {
//                                    infoBo.setStreet(poi);
//                                }


                            }else if(item.getString("LOCATION_C").indexOf("台湾")>0)
                            {
                                infoBo.setDisaster_address(item.getString("LOCATION_C"));
                                infoBo.setProvince("台湾省");
                                if(item.getString("LOCATION_C").indexOf("省")>0)
                                {
                                    infoBo.setProvince(item.getString("LOCATION_C").substring(0,item.getString("LOCATION_C").indexOf("省")+1));
                                }
                                infoBo.setCity("");
                                if(item.getString("LOCATION_C").indexOf("市")>0)
                                {
                                    infoBo.setProvince(item.getString("LOCATION_C").substring(0,item.getString("LOCATION_C").indexOf("市")+1));
                                }
                                infoBo.setDistrict("");
                                if(item.getString("LOCATION_C").indexOf("县")>0)
                                {
                                    infoBo.setProvince(item.getString("LOCATION_C").substring(0,item.getString("LOCATION_C").indexOf("县")+1));
                                }
//                                infoBo.setStreet("");
//                                if(item.getString("LOCATION_C").indexOf("路")>0)
//                                {
//                                    infoBo.setProvince(item.getString("LOCATION_C").substring(0,item.getString("LOCATION_C").indexOf("路")+1));
//                                }
                            }else
                            {
                                infoBo.setProvince("国外");
                                infoBo.setCity("国外");
                                infoBo.setDistrict("国外");
                                //infoBo.setStreet("国外");
                                infoBo.setDisaster_address("国外");
                            }
                            if(infoBo.getProvince()==null||infoBo.getProvince().equals("")) {
                                infoBo.setProvince( "国外" );
                                infoBo.setCity("国外");
                                infoBo.setDistrict("国外");
                                infoBo.setDisaster_address("国外");
                            }

                            if((infoBo.getCity()==null||infoBo.getCity().equals(""))&&infoBo.getDistrict()!=null)
                            {
                                infoBo.setCity(infoBo.getDistrict());
                            }
                            infoBo.setDisaster_status("灾害");
                            String prefix=Double.valueOf(item.getString("EPI_LON"))>0?"东经":"西经";
                            String prefixs=Double.valueOf(item.getString("EPI_LAT"))>0?"北纬":"南纬";

                            infoBo.setInformationcontent(startDate+" "+item.getString("LOCATION_C")+"【"+prefix+ Math.abs((Double.valueOf(item.getString("EPI_LON"))))+
                               ","+ prefixs+Math.abs((Double.valueOf(item.getString("EPI_LAT"))))+" 】发生了"+item.getString("M")+"级地震，震源深度"+item.getString("EPI_DEPTH")+"千米。");

                            List<String> sendUser=new ArrayList<>();
                            // 发送内容
                           String emileSend= propertiesProxy.get("email.Send");
                           if(StrUtil.isNotBlank(emileSend)){
                               sendUser=Arrays.asList(emileSend.split(","));
                           }
                        CompletableFuture[] cf = sendUser.stream().map(emile -> CompletableFuture.runAsync(() ->
                                        emailSendServer.sendMsg("用户" ,infoBo.getInformationtitle(), emile, infoBo.getInformationcontent()), taskQueryExecutor)
                                .thenApply(r -> r)).toArray(CompletableFuture[]::new);

                            //MailUtils.sendText("1750632126@qq.com,yiyi5475@163.com,2607419919@qq.com",infoBo.getInformationtitle(),infoBo.getInformationcontent());
                            infoBo.setInformationmedia("中国地震台网");
                            infoBo.setInformationchannels("中国地震台网");

                            infoBo.setDisaster_type("地震");;
                            infoBo.setLongitude(item.getString("EPI_LON"));
                            infoBo.setLatitude(item.getString("EPI_LAT"));
                            infoBo.setDisaster_class(item.getString("M"));
                            //infoBo.setPicurl("震源深度"+item.getString("EPI_DEPTH")+"千米。");
                            infoBo.setPicurl("dizheng.png");
                            infoBo.setAddperson("祥云AI");
                            infoBo.setAddphone("18888888888");
                            infoBo.setIsshow("0");
                            infoBo.setCreatedate(new Date());

                                Date day=new Date();
                                SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                infoBo.setAddtime(sdf.format(day));
                                emergencyInfoList.add(infoBo);
                        //wxSpiderEmergencyInformationService.insert(infoBo);
                    }
                }
                if(CollectionUtil.isNotEmpty(emergencyInfoList)){
                    wxSpiderEmergencyInformationService.fastInsert(emergencyInfoList);
                }
            } catch(Exception e) {
                e.printStackTrace();
            }

        } catch(Exception e) {
            e.printStackTrace();
        }
    }




}
